package com.lifeverse.controller;

import com.lifeverse.common.ApiResponse;
import com.lifeverse.dto.ConsciousnessStateCreateDTO;
import com.lifeverse.dto.ConsciousnessStateDTO;
import com.lifeverse.dto.ConsciousnessStateUpdateDTO;
import com.lifeverse.entity.ConsciousnessState;
import com.lifeverse.service.ConsciousnessService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 意识状态管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/consciousness")
@RequiredArgsConstructor
@Tag(name = "意识状态管理", description = "生命体意识状态的创建、查询、更新和管理")
public class ConsciousnessController {
    
    private final ConsciousnessService consciousnessService;
    
    /**
     * 创建意识状态
     */
    @PostMapping
    @Operation(summary = "创建意识状态", description = "为生命体创建新的意识状态记录")
    public ResponseEntity<ApiResponse<ConsciousnessStateDTO>> createConsciousnessState(
            @Valid @RequestBody ConsciousnessStateCreateDTO createDTO) {
        log.info("接收创建意识状态请求: {}", createDTO);
        
        ConsciousnessStateDTO result = consciousnessService.createConsciousnessState(createDTO);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(ApiResponse.success(result, "意识状态创建成功"));
    }
    
    /**
     * 根据ID查询意识状态
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询意识状态", description = "根据ID查询特定的意识状态详情")
    public ResponseEntity<ApiResponse<ConsciousnessStateDTO>> getConsciousnessState(
            @Parameter(description = "意识状态ID") @PathVariable Long id) {
        log.info("接收查询意识状态请求，ID: {}", id);
        
        ConsciousnessStateDTO result = consciousnessService.getConsciousnessStateById(id);
        return ResponseEntity.ok(ApiResponse.success(result, "查询成功"));
    }
    
    /**
     * 更新意识状态
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新意识状态", description = "更新指定ID的意识状态信息")
    public ResponseEntity<ApiResponse<ConsciousnessStateDTO>> updateConsciousnessState(
            @Parameter(description = "意识状态ID") @PathVariable Long id,
            @Valid @RequestBody ConsciousnessStateUpdateDTO updateDTO) {
        log.info("接收更新意识状态请求，ID: {}, 更新数据: {}", id, updateDTO);
        
        ConsciousnessStateDTO result = consciousnessService.updateConsciousnessState(id, updateDTO);
        return ResponseEntity.ok(ApiResponse.success(result, "意识状态更新成功"));
    }
    
    /**
     * 结束意识状态
     */
    @PostMapping("/{id}/end")
    @Operation(summary = "结束意识状态", description = "结束指定ID的意识状态，设置结束时间并计算持续时间")
    public ResponseEntity<ApiResponse<ConsciousnessStateDTO>> endConsciousnessState(
            @Parameter(description = "意识状态ID") @PathVariable Long id) {
        log.info("接收结束意识状态请求，ID: {}", id);
        
        ConsciousnessStateDTO result = consciousnessService.endConsciousnessState(id);
        return ResponseEntity.ok(ApiResponse.success(result, "意识状态结束成功"));
    }
    
    /**
     * 删除意识状态
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除意识状态", description = "软删除指定ID的意识状态")
    public ResponseEntity<ApiResponse<Void>> deleteConsciousnessState(
            @Parameter(description = "意识状态ID") @PathVariable Long id) {
        log.info("接收删除意识状态请求，ID: {}", id);
        
        consciousnessService.deleteConsciousnessState(id);
        return ResponseEntity.ok(ApiResponse.success(null, "意识状态删除成功"));
    }
    
    /**
     * 根据生命体ID查询意识状态列表
     */
    @GetMapping("/life-entity/{lifeEntityId}")
    @Operation(summary = "查询生命体的意识状态", description = "根据生命体ID查询其所有意识状态记录")
    public ResponseEntity<ApiResponse<List<ConsciousnessStateDTO>>> getConsciousnessStatesByLifeEntity(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId) {
        log.info("接收查询生命体意识状态请求，生命体ID: {}", lifeEntityId);
        
        List<ConsciousnessStateDTO> result = consciousnessService.getConsciousnessStatesByLifeEntity(lifeEntityId);
        return ResponseEntity.ok(ApiResponse.success(result, "查询成功"));
    }
    
    /**
     * 根据生命体ID和状态类型查询意识状态列表
     */
    @GetMapping("/life-entity/{lifeEntityId}/type/{stateType}")
    @Operation(summary = "查询生命体特定类型的意识状态", description = "根据生命体ID和状态类型查询意识状态记录")
    public ResponseEntity<ApiResponse<List<ConsciousnessStateDTO>>> getConsciousnessStatesByLifeEntityAndType(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId,
            @Parameter(description = "状态类型") @PathVariable ConsciousnessState.StateType stateType) {
        log.info("接收查询生命体特定类型意识状态请求，生命体ID: {}, 状态类型: {}", lifeEntityId, stateType);
        
        List<ConsciousnessStateDTO> result = consciousnessService.getConsciousnessStatesByLifeEntityAndType(lifeEntityId, stateType);
        return ResponseEntity.ok(ApiResponse.success(result, "查询成功"));
    }
    
    /**
     * 查询活跃的意识状态
     */
    @GetMapping("/active")
    @Operation(summary = "查询活跃的意识状态", description = "查询所有当前活跃（未结束）的意识状态")
    public ResponseEntity<ApiResponse<List<ConsciousnessStateDTO>>> getActiveConsciousnessStates() {
        log.info("接收查询活跃意识状态请求");
        
        List<ConsciousnessStateDTO> result = consciousnessService.getActiveConsciousnessStates();
        return ResponseEntity.ok(ApiResponse.success(result, "查询成功"));
    }
    
    /**
     * 根据生命体ID查询活跃的意识状态
     */
    @GetMapping("/active/life-entity/{lifeEntityId}")
    @Operation(summary = "查询生命体的活跃意识状态", description = "根据生命体ID查询其当前活跃的意识状态")
    public ResponseEntity<ApiResponse<List<ConsciousnessStateDTO>>> getActiveConsciousnessStatesByLifeEntity(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId) {
        log.info("接收查询生命体活跃意识状态请求，生命体ID: {}", lifeEntityId);
        
        List<ConsciousnessStateDTO> result = consciousnessService.getActiveConsciousnessStatesByLifeEntity(lifeEntityId);
        return ResponseEntity.ok(ApiResponse.success(result, "查询成功"));
    }
    
    /**
     * 查询异常的意识状态
     */
    @GetMapping("/anomalous")
    @Operation(summary = "查询异常的意识状态", description = "查询所有被标记为异常的意识状态")
    public ResponseEntity<ApiResponse<List<ConsciousnessStateDTO>>> getAnomalousConsciousnessStates() {
        log.info("接收查询异常意识状态请求");
        
        List<ConsciousnessStateDTO> result = consciousnessService.getAnomalousConsciousnessStates();
        return ResponseEntity.ok(ApiResponse.success(result, "查询成功"));
    }
    
    /**
     * 查询高强度的意识状态
     */
    @GetMapping("/high-intensity")
    @Operation(summary = "查询高强度的意识状态", description = "查询强度级别超过指定阈值的意识状态")
    public ResponseEntity<ApiResponse<Page<ConsciousnessStateDTO>>> getHighIntensityConsciousnessStates(
            @Parameter(description = "最小强度级别") @RequestParam(defaultValue = "80.0") BigDecimal minIntensity,
            @PageableDefault(size = 20) Pageable pageable) {
        log.info("接收查询高强度意识状态请求，最小强度: {}", minIntensity);
        
        Page<ConsciousnessStateDTO> result = consciousnessService.getHighIntensityConsciousnessStates(minIntensity, pageable);
        return ResponseEntity.ok(ApiResponse.success(result, "查询成功"));
    }
    
    /**
     * 查询最近的意识状态
     */
    @GetMapping("/recent")
    @Operation(summary = "查询最近的意识状态", description = "查询指定时间点之后的所有意识状态")
    public ResponseEntity<ApiResponse<List<ConsciousnessStateDTO>>> getRecentConsciousnessStates(
            @Parameter(description = "起始时间") 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime since) {
        log.info("接收查询最近意识状态请求，起始时间: {}", since);
        
        List<ConsciousnessStateDTO> result = consciousnessService.getRecentConsciousnessStates(since);
        return ResponseEntity.ok(ApiResponse.success(result, "查询成功"));
    }
    
    /**
     * 查询需要关注的意识状态
     */
    @GetMapping("/attention-needed")
    @Operation(summary = "查询需要关注的意识状态", description = "查询异常或低质量的意识状态")
    public ResponseEntity<ApiResponse<List<ConsciousnessStateDTO>>> getConsciousnessStatesNeedingAttention(
            @Parameter(description = "质量阈值") @RequestParam(defaultValue = "50.0") BigDecimal qualityThreshold) {
        log.info("接收查询需要关注的意识状态请求，质量阈值: {}", qualityThreshold);
        
        List<ConsciousnessStateDTO> result = consciousnessService.getConsciousnessStatesNeedingAttention(qualityThreshold);
        return ResponseEntity.ok(ApiResponse.success(result, "查询成功"));
    }
    
    /**
     * 根据时间段查询意识状态
     */
    @GetMapping("/time-period")
    @Operation(summary = "查询时间段内的意识状态", description = "查询指定时间段内的所有意识状态")
    public ResponseEntity<ApiResponse<List<ConsciousnessStateDTO>>> getConsciousnessStatesByTimePeriod(
            @Parameter(description = "开始时间") 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        log.info("接收查询时间段意识状态请求，开始时间: {}, 结束时间: {}", startTime, endTime);
        
        List<ConsciousnessStateDTO> result = consciousnessService.getConsciousnessStatesByTimePeriod(startTime, endTime);
        return ResponseEntity.ok(ApiResponse.success(result, "查询成功"));
    }
}